<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter中factory的使用总结》 - 飞雪无情的博客</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Java、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Flutter中factory的使用总结》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.flysnow.org/posts/flutter/flutter%E4%B8%ADfactory%E7%9A%84%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93/" />
<meta property="article:published_time" content="2021-07-30T22:53:26+08:00" />
<meta property="article:modified_time" content="2021-07-30T22:53:26+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Flutter中factory的使用总结》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="飞雪无情的博客">
<meta name="apple-mobile-web-app-title" content="飞雪无情的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://www.flysnow.org/posts/flutter/flutter%E4%B8%ADfactory%E7%9A%84%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93/" /><link rel="prev" href="https://www.flysnow.org/posts/flutter/%E5%BC%80%E5%8F%91flutter%E6%9C%89%E5%93%AA%E4%BA%9B%E5%A5%BD%E7%94%A8%E7%9A%84VsCode%E6%8F%92%E4%BB%B6/" /><link rel="next" href="https://www.flysnow.org/posts/ios/ios%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93%E6%B1%87%E6%80%BB/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter中factory的使用总结》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/www.flysnow.org\/posts\/flutter\/flutter%E4%B8%ADfactory%E7%9A%84%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93\/"
        },"genre": "posts","keywords": "flutter","wordcount":  521 ,
        "url": "https:\/\/www.flysnow.org\/posts\/flutter\/flutter%E4%B8%ADfactory%E7%9A%84%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93\/","datePublished": "2021-07-30T22:53:26+08:00","dateModified": "2021-07-30T22:53:26+08:00","publisher": {
            "@type": "Organization",
            "name": "飞雪无情"},"author": {
                "@type": "Person",
                "name": "飞雪无情"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">飞雪无情的博客</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/tools/">工具</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/archives/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter中factory的使用总结》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>飞雪无情</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-30">2021-07-30</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;521 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;2 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#0x01官方描述">0x01官方描述</a></li>
    <li><a href="#0x02使用场景">0x02使用场景</a></li>
    <li><a href="#0x03-demo">0x03 Demo</a>
      <ul>
        <li><a href="#创建缓存实例">创建缓存实例</a></li>
        <li><a href="#调用子类的构造函数">调用子类的构造函数</a></li>
        <li><a href="#实现单例模式">实现单例模式</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<h2 id="0x01官方描述">0x01官方描述</h2>
<blockquote>
<p>Use the <code>factory</code> keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype.</p>
<p>当实现并非总是创建其类的新实例的构造函数时，请使用“ factory”关键字。例如，工厂构造函数可能会从缓存返回一个实例，或者可能会返回一个子类型的实例。</p>
</blockquote>
<h2 id="0x02使用场景">0x02使用场景</h2>
<ol>
<li>避免创建过多的重复实例，如果该实例已创建，则直接从缓存获取。</li>
<li>调用子类的构造函数(工厂模式 factory pattern）</li>
<li>实现单例模式(singleton pattern)</li>
</ol>
<h2 id="0x03-demo">0x03 Demo</h2>
<h3 id="创建缓存实例">创建缓存实例</h3>
<blockquote>
<p>引用自 <a href="https://dart.dev/guides/language/language-tour#factory-constructors">https://dart.dev/guides/language/language-tour#factory-constructors</a></p>
</blockquote>
<pre><code>class Logger {
  final String name;
  // 缓存Map
  static final Map&lt;String, Logger&gt; _cache = &lt;String, Logger&gt;{};

  factory Logger(String name) {
    // name对应的key在_cache不存在，执行Logger._internal(name)，否则直接返回
    return _cache.putIfAbsent(name, () =&gt; Logger._internal(name));
  }

  // 私有构造函数
  Logger._internal(this.name) {
    print('生成新实例:$name');
  }
}

void main(List&lt;String&gt; args) {
  var p1 = Logger('1');
  var p2 = Logger('2');
  var p3 = Logger('1');
  print(identical(p1, p2));
  print(identical(p1, p3));
  // 生成新实例:1
  // 生成新实例:2
  // false
  // true
}
</code></pre><h3 id="调用子类的构造函数">调用子类的构造函数</h3>
<pre><code>abstract class Animal extends Object {
  String name;
  void getNoise();
  factory Animal(String type, String name) {
    switch (type) {
      case 'cat':
        return Cat(name);
        break;
      case 'dog':
        return Dog(name);
        break;
      default:
        throw &quot;The '$type' is not an animal&quot;;
    }
  }
}

class Cat implements Animal {
  String name;
  Cat(this.name);
  @override
  void getNoise() {
    print('${this.name}:mew~');
  }
}

class Dog implements Animal {
  String name;
  Dog(this.name);
  @override
  void getNoise() {
    print('${this.name}:wang~');
  }
}

void main(List&lt;String&gt; args) {
  var cat = Animal('cat', 'haha');
  var dog = Animal('dog', 'hehe');
  cat.getNoise();
  dog.getNoise();
  // haha:mew~
  // hehe:wang~
}
</code></pre><h3 id="实现单例模式">实现单例模式</h3>
<pre><code>class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

void main(List&lt;String&gt; args) {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));
  // true
}
</code></pre></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-07-30</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/%E5%BC%80%E5%8F%91flutter%E6%9C%89%E5%93%AA%E4%BA%9B%E5%A5%BD%E7%94%A8%E7%9A%84VsCode%E6%8F%92%E4%BB%B6/" class="prev" rel="prev" title="《开发flutter有哪些好用的VsCode插件》"><i class="fas fa-angle-left fa-fw"></i>《开发flutter有哪些好用的VsCode插件》</a>
            <a href="/posts/ios/ios%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93%E6%B1%87%E6%80%BB/" class="next" rel="next" title="《Ios第三方库汇总》">《Ios第三方库汇总》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">飞雪无情</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
